import { useState } from 'react';
import { CheckCircle, AlertCircle, Check, RotateCw, FileText, ArrowRight } from 'lucide-react';
import { useTemplate } from '@/contexts/template';
import { getAssessmentTypeDisplay } from '@/types/template';

type ImportSummaryProps = {
  onBack: () => void;
};

type ImportStatus = 'idle' | 'creating' | 'success' | 'error';

export function ImportSummary({ onBack }: ImportSummaryProps) {
  const { state, createNewTemplate, resetTemplate } = useTemplate();
  const [importStatus, setImportStatus] = useState<ImportStatus>('idle');
  const [error, setError] = useState<string | null>(null);

  const handleDone = () => {
    resetTemplate();
    onBack();
  };

  const handleCreateTemplate = async () => {
    if (!state.currentTemplate) {
      setError('没有可用的模板数据');
      setImportStatus('error');
      return;
    }

    setImportStatus('creating');
    setError(null);

    try {
      await createNewTemplate({
        name: state.currentTemplate.name || '',
        description: state.currentTemplate.description || '',
        assessmentType: state.currentTemplate.assessment_type || '101',
        items: state.currentTemplate.items || [],
        defaultMaturityLevel: state.currentTemplate.default_maturity_level
      });
      setImportStatus('success');
    } catch (err) {
      console.error('创建模板失败:', err);
      setError('创建模板失败，请重试。');
      setImportStatus('error');
    }
  };

  const isComplete = importStatus === 'success' || importStatus === 'error';
  const { currentTemplate } = state;

  return (
    <div className="space-y-6">
      <div className="text-center">
        <h2 className="text-2xl font-bold">创建摘要</h2>
        <p className="text-muted-foreground">
          {importStatus === 'idle' && '请检查模板信息，然后确认创建。'}
          {importStatus === 'creating' && '正在创建模板...'}
          {importStatus === 'success' && '模板已成功创建！'}
          {importStatus === 'error' && '模板创建失败。'}
        </p>
      </div>

      {importStatus === 'idle' && currentTemplate && (
        <div className="rounded-lg border bg-card p-6 text-card-foreground shadow-sm">
          <div className="flex items-center space-x-4">
            <FileText className="h-8 w-8 text-primary" />
            <div>
              <h3 className="text-lg font-semibold">{currentTemplate.name}({getAssessmentTypeDisplay(currentTemplate.assessment_type)})</h3>
              <p className="text-sm text-muted-foreground">{currentTemplate.description}</p>
            </div>
          </div>
          <div className="mt-4 border-t pt-4 space-y-2">
            <p className="text-sm font-medium">
              共包含 {currentTemplate.items?.length || 0} 个检查项。
            </p>
            {currentTemplate.assessment_type === '105' && currentTemplate.default_maturity_level && (
              <p className="text-sm font-medium text-slate-600">
                默认成熟度等级：{currentTemplate.default_maturity_level} 级
              </p>
            )}
          </div>
        </div>
      )}

      {importStatus === 'creating' && (
        <div className="flex flex-col items-center justify-center space-y-4 p-6">
          <RotateCw className="h-12 w-12 animate-spin text-primary" />
          <p className="text-muted-foreground">正在处理中，请稍候...</p>
        </div>
      )}

      {isComplete && (
        <div className="rounded-lg border p-6 text-center">
          {importStatus === 'success' ? (
            <div className="space-y-4">
              <div className="mx-auto flex h-12 w-12 items-center justify-center rounded-full bg-green-100">
                <CheckCircle className="h-8 w-8 text-green-600" />
              </div>
              <h3 className="text-lg font-medium">创建成功！</h3>
              <p className="text-muted-foreground">
                模板已成功创建。
              </p>
            </div>
          ) : (
            <div className="space-y-4">
              <div className="mx-auto flex h-12 w-12 items-center justify-center rounded-full bg-red-100">
                <AlertCircle className="h-8 w-8 text-red-600" />
              </div>
              <h3 className="text-lg font-medium">创建失败</h3>
              <p className="text-muted-foreground">
                {error || '创建模板时发生未知错误。'}
              </p>
            </div>
          )}
        </div>
      )}

      <div className="flex justify-end space-x-4">
        {importStatus === 'idle' && (
          <button
            type="button"
            onClick={handleCreateTemplate}
            className="inline-flex items-center justify-center rounded-md bg-primary px-4 py-2 text-sm font-medium text-primary-foreground shadow-sm transition-colors hover:bg-primary-hover focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2"
          >
            确认并创建
            <ArrowRight className="ml-2 h-4 w-4" />
          </button>
        )}
        
        {isComplete && (
          <button
            type="button"
            onClick={handleDone}
            className="inline-flex items-center justify-center rounded-md bg-primary px-4 py-2 text-sm font-medium text-primary-foreground shadow-sm transition-colors hover:bg-primary-hover focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2"
          >
            <Check className="mr-2 h-4 w-4" />
            完成
          </button>
        )}
      </div>
    </div>
  );
}
